package edu.office.applicationRepository;


import edu.office.entities.Resourceinfo;
import edu.office.entities.Roleinfo;
import edu.office.tools.EOMessage;
import edu.office.tools.EOMessage1;
import io.quarkus.panache.common.Sort;
import io.quarkus.security.Authenticated;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import org.eclipse.microprofile.jwt.JsonWebToken;

import java.util.*;

@Path("/resourceinfo")
@Named("resourceinfoRepositoryA")
@ApplicationScoped
public class ResourceinfoRepository extends ApplicationCommonRepository<Resourceinfo> {


    @Inject
    RoleinfoRepository roleinfoRepository;
    List<Resourceinfo> firstLevel;
    HashMap<Integer, Integer> roleMap = new HashMap<>();
    @Inject
    JsonWebToken jwt;
    private HashMap<Roleinfo, List<ResourceTree>> roleResouceList = new HashMap<>();
    private List<Resourceinfo> allResourceinfos = new LinkedList<>();
    private HashMap<Resourceinfo, List<Resourceinfo>> hierachyResouceinfo = new HashMap<>();

    public Resourceinfo findByName(String name) {
        Resourceinfo result = null;
        for (Resourceinfo resourceinfo : getAllList()) {
            if (resourceinfo.getNAME().trim().equals(name.trim())) {
                result = resourceinfo;
            }
        }
        return result;
    }

    public Resourceinfo findByValueinfo(String valueinfo) {
        Resourceinfo result = null;
        for (Resourceinfo resourceinfo : getAllList()) {
            if (resourceinfo.getVALUEINFO().trim().equals(valueinfo.trim())) {
                result = resourceinfo;
            }
        }
        return result;
    }

    private void calcuRoleResourceList() {
        roleResouceList.clear();
        List<Roleinfo> allRoleinfos = roleinfoRepository.listAll();
        allRoleinfos.forEach((role) -> roleResouceList.put(role, new LinkedList<>()));
        for (Roleinfo role : allRoleinfos) {
            List<String> resoursIds = Arrays.asList((roleinfoRepository.getRoleById(role.getID()).getRESOURCES()).split(","));
            List<ResourceTree> tem = new LinkedList<>();
            for (Resourceinfo resourceinfo : firstLevelResoure()) {//获得父结点，
                ResourceTree childrenResource = new ResourceTree();
                childrenResource.setChildren(new LinkedList<>());
                List<Resourceinfo> forTem = find("PARENTID", resourceinfo.getID()).list();
                for (Resourceinfo child : forTem) {//下面只对其子结点进行过滤
                    if (resoursIds.contains(child.getID().toString())) {//子结点中属于当用角色的功能，则放入
                        childrenResource.getChildren().add(child);
                    }
                }
                if (!childrenResource.getChildren().isEmpty()) {
                    childrenResource.setRoot(resourceinfo);
                    tem.add(childrenResource);
                }
            }
            tem.sort(new ResourceTree());
            tem.forEach((ele) -> ele.getChildren().sort(Comparator.comparingInt(Resourceinfo::getMENUORDER)));
            roleResouceList.put(role, tem);
        }
    }

    private List<Resourceinfo> firstLevelResoure() {
        if (null == firstLevel) {
            firstLevel = find("PARENTID is null", Sort.by("MENUORDER")).list();
        }
        return firstLevel;
    }

    @Path("/resmap")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Authenticated
    public List<ResourceTree> getResMap() {
        Set<String> groups = jwt.getGroups();
        String roleId = "";
        for (String group : groups) {
            if (group.substring(0, 1).equals("l")) {
                roleId = group.substring(2);
                break;
            }
        }
        if (roleId == null || roleId.isEmpty()) {
            return new LinkedList<>();
        } else {
            Roleinfo roleinfo=roleinfoRepository.getRoleById(getRoleMap().get(Integer.valueOf(roleId)));
            if (roleinfo==null) {
                return new LinkedList<>();
            } else {
                return getRoleResouceMap().get(roleinfo);
            }
        }
    }

    public HashMap<Roleinfo, List<ResourceTree>> getRoleResouceMap() {
        if (roleResouceList.isEmpty()) {
            calcuRoleResourceList();
        }
        return roleResouceList;
    }

    public HashMap<Resourceinfo, List<Resourceinfo>> getHierachyResouceinfo() {
        if (hierachyResouceinfo.isEmpty()) {
            for (Resourceinfo resourceinfo : getAllList()) {
                if (resourceinfo.getPARENTID() == null) {
                    hierachyResouceinfo.put(resourceinfo, new LinkedList<>(find("PARENTID", resourceinfo.getID()).list()));
                }
            }
        }
        return hierachyResouceinfo;
    }

    public Set<Resourceinfo> getAllSet() {
        return new HashSet<>(getAllList());
    }

    public List<Resourceinfo> getAllList() {//由于菜单几乎不变化，所以不再重新获取
        if (this.allResourceinfos.isEmpty()) {
            allResourceinfos = listAll();
        }
        return allResourceinfos;
    }

    public void resetResourceinfo() {
        allResourceinfos.clear();
    }

    public void refresh() {
        roleResouceList.clear();
    }

    public List<String> getRoleResourceNames(Roleinfo roleinfo) {
        List<String> result = new LinkedList<>();
        for (Resourceinfo resourceinfo : getTemResourceinfoList(roleinfo)) {
            result.add(resourceinfo.getNAME());
        }
        return result;
    }

    public List<Resourceinfo> getTemResourceinfoList(Roleinfo roleinfo) {
        List<Resourceinfo> temResourceinfoList = new LinkedList<>();
        List<ResourceTree> temMap = getRoleResouceMap().get(roleinfo);
        temMap.forEach((elem) -> {
            temResourceinfoList.addAll(elem.getChildren());
        });
        return temResourceinfoList;
    }
//=================

    public String mycreate(Resourceinfo resourceinfo) {
        if (list("NAME", resourceinfo.getNAME()).isEmpty()) {
            create(resourceinfo);
            return EOMessage.getEOMessageENUM(EOMessage1.Succeed);
        } else {
            return EOMessage.getEOMessageENUM(EOMessage1.Already_Exist);
        }
    }

    private HashMap<Integer, Integer> getRoleMap() {
        //从页面返回数据后，要找到对应的在数据库中的编号，前边int是从页面返回的，后面的int是数据库中的
        if (roleMap.isEmpty()) {
            roleMap.put(6, 2);
            roleMap.put(5, 113);
            roleMap.put(1, 3);
            roleMap.put(2, 1);
            roleMap.put(3, 109);
            roleMap.put(4, 112);
        }
        return roleMap;
    }
}
